package shared;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Contacts {
	
	public static ArrayList<User> contacts=new ArrayList<User>();
	
	public void addContact(String name, String IP, String Port){
		User user=new User(name,IP,Port);
		contacts.add(user);
	}
	public User getContact(String name){
		
		for(int s=0;s<contacts.size();s++){
			
			User user=contacts.get(s);
			if(user.getName().equals(name))
				return user;
			
		}
		return null;
	}
	
	public ArrayList<User> getAllContacts(){
		return contacts;
	}
	
	
	public void readFromFile(){
		String returnValue = "";
		  FileReader file = null;
		  
		  try {
		    file = new FileReader("C:\\contacts.txt");
		    BufferedReader reader = new BufferedReader(file);
		    String line = "";
		    while ((line = reader.readLine()) != null) {
		      returnValue += line + "\n";
		    }
		  } catch (FileNotFoundException e) {
		      throw new RuntimeException("File not found");
		  } catch (IOException e) {
		      throw new RuntimeException("IO Error occured");
		  } finally {
		    if (file != null) {
		      try {
		        file.close();
		      } catch (IOException e) {
		        e.printStackTrace();
		      }
		    }
		  }		
	}
	public void writeTextFile() {
		String fileName="C:\\contacts.txt";
	    FileWriter output = null;
	    try {
	      output = new FileWriter(fileName);
	      BufferedWriter writer = new BufferedWriter(output);
	      writer.write("[\n");
	      for(int s=0;s<contacts.size();s++){
	    	  
	    	User user=contacts.get(s);
	    	String name=user.getName();
	    	String IP=user.getIP();
	    	String port=user.getPort();
	    	writer.write("[\n");
	    	writer.write('"');
	    	writer.write(name);
	    	writer.write('"');
	    	writer.write(",");
	    	writer.write('"');
	    	writer.write(IP);
	    	writer.write('"');
	    	writer.write(",");
	    	writer.write('"');
	    	writer.write(port);
	    	writer.write('"');
	    	writer.write("n]");
	    	writer.write(",");
	      }	      
	      
	      writer.write("\n]");
	    } catch (IOException e) {
	      e.printStackTrace();
	    } finally {
	      if (output != null) {
	        try {
	          output.close();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }

	  }

}
